package com.wjy.game;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Objects;

import javax.imageio.ImageIO;

import lombok.extern.slf4j.Slf4j;

/**
 * 客户端服务器
 * 
 * @author Administrator
 */
@Slf4j
public class MultiClientServer extends Frame implements ActionListener {

    private final Button clearButton = new Button("清除显示");
    private final Button statusButton = new Button("服务器状态");
    private final Button closeButton = new Button("关闭服务器");

    @Override
    public void setLayout(LayoutManager mgr) {
        super.setLayout(null);
    }

    @Override
    public void setBackground(Color bgColor) {
        super.setBackground(Color.WHITE);
    }

    /**
     * 信息服务
     */
    MessageBoard server = new MessageBoard();

    /**
     * 服务器套接字
     */
    ServerSocket serverSocket;

    /**
     * 客户端数据哈希表
     */
    Hashtable<Object, Object> clientDataHash = new Hashtable<Object, Object>(50);

    /**
     * 客户端名称哈希表
     */
    Hashtable<Object, String> clientNameHash = new Hashtable<Object, String>(50);

    /**
     * 客户端颜色哈希表
     */
    Hashtable<Object, String> clientColorHash = new Hashtable<Object, String>(50);

    /**
     * 房间占位标识
     */
    String[] inChess = new String[50];

    /**
     * 房间号
     */
    int[] roomNum = new int[1];

    MultiClientServer() {
        super("五子棋服务器");
        // 设置窗口图标
        try {
            Image icon = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("img.png")));
            setIconImage(icon);
        } catch (IOException e) {
            log.error("无法加载图标文件: {}", e.getMessage());
        }
        // 初始化房间占位标识
        for (int i = 0; i < 50; i++) {
            inChess[i] = "0";
        }
        setLayout(null);
        /**
         * 按钮面板
         */
        Panel buttonPanel = new Panel();
        buttonPanel.setBounds(0, 330, 300, 50);

        buttonPanel.setLayout(new FlowLayout());
        clearButton.setSize(20, 25);
        buttonPanel.add(clearButton);
        clearButton.addActionListener(this);
        statusButton.setSize(75, 25);
        buttonPanel.add(statusButton);
        statusButton.addActionListener(this);
        closeButton.setSize(75, 25);
        buttonPanel.add(closeButton);
        closeButton.addActionListener(this);

        // 添加消息服务到窗口中间
        add(server, BorderLayout.CENTER);

        // 添加按钮面板到窗口底部
        add(buttonPanel, BorderLayout.SOUTH);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        // 弹出窗口
        pack();
        // 窗口位置
        setLocation(534, 230);
        // 窗口显示
        setVisible(true);
        // 窗口大小
        setSize(300, 380);
        // 窗口不可改变大小
        setResizable(false);
        // 布局验证
        validate();
        try {
            log.info("开始启动服务器.....");
            makeMessageServer(5024, server);
        } catch (Exception e) {
            log.error("服务器启动发生错误: {}", e.getMessage());
        }
    }

    public void makeMessageServer(int port, MessageBoard server) throws IOException {
        Socket clientSocket;
        this.server = server;

        try {
            serverSocket = new ServerSocket(port);
            serverSocket.getInetAddress();
            server.getMessageBoard()
                .setText("服务器:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n");

            while (true) {
                clientSocket = serverSocket.accept();
                server.getMessageBoard().append("用户连接:" + clientSocket + "\n");

                DataOutputStream outData = new DataOutputStream(clientSocket.getOutputStream());
                clientColorHash.put(clientSocket, "-1");
                clientDataHash.put(clientSocket, outData);
                Server thread =
                    new Server(clientSocket, clientDataHash, clientNameHash, roomNum, inChess, server, clientColorHash);
                thread.start();
            }
        } catch (IOException ex) {
            log.info("已经有服务器在运行.");
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clearButton) {
            server.getMessageBoard().setText("");
        }
        if (e.getSource() == statusButton) {
            try {
                serverSocket.getInetAddress();
                server.getMessageBoard()
                    .append("服务器信息:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n");
            } catch (Exception ee) {
                log.error("serverSocket.getInetAddress().getLocalHost() error \n");
            }
        }
        if (e.getSource() == closeButton) {
            System.exit(0);
        }
    }

}
